<template>
	<!-- 导入组件 -->
	<lay-layer v-model="visible" :title="title" :shade-opacity="0.5" :shade-close="false" :area="area" :btn="action">
		<div class="padding-lg">
			<lay-json-schema-form ref="formRef" :model="formData" :useCN="true" :schema="formSchema" space="2">
				<!-- 导入第几张表 -->
				<template #SheetIndex>
					<lay-input-number v-model="formData.SheetIndex" :step="1" position="right"></lay-input-number>
				</template>
				<!-- 从第几行导入 -->
				<template #RowIndex>
					<div class="flex align-center">
						<lay-input-number v-model="formData.RowIndex" :step="1" position="right"></lay-input-number>
						<span class="margin-left text-gray">该行的上一行，为匹配行</span>
					</div>
				</template>

				<!-- 文件路径 -->
				<template #filename>
					<div class="flex align-center">
						<lay-input v-model="formData.filename" :disabled="true">
							<template #append="{ disabled }">
								<lay-upload :key="layUploadKey" @on-change="onChange" :auto="false" :number="1" class="flex align-center justify-center">
									<template v-slot:default="params">
										选择文件
									</template>
								</lay-upload>
							</template>
						</lay-input>
						<lay-button @click="onUpload" type="normal" prefix-icon="layui-icon-upload" class="margin-left">读取数据</lay-button>
					</div>
				</template>

				<!-- 导入模板 -->
				<template #importTemplate>
					<div class="flex align-center" style="height: 38px;">
						<a class="text-blue2 cursor" :href="fileUrl">{{importFileName}}</a>
					</div>
				</template>
			</lay-json-schema-form>

			<lay-line contentPosition="left">
				<span class="text-xl">匹配结果</span>
			</lay-line>

			<!-- 表格 -->
			<div class="margin-top-lg margin-bottom-lg text-orange">
				<lay-icon type="layui-icon-tips-fill"></lay-icon> 点击单元格，可直接修改数据
			</div>
			<pol-table :key="polTableKey" ref="polTableRef" v-bind="tableOpt">
				<!-- 字段名 -->
				<template v-for="(item, index) in tableOpt.columns" :key="index" #[item.key]="{ row, rowIndex }">
					<div v-if="item.key === 'remove'">
						<lay-button size="xs" type="danger" @click="removeRow(rowIndex)">删除</lay-button>
					</div>
					<div v-else>
						<lay-input v-model="row[item.key]" placeholder="" />
					</div>
				</template>
			</pol-table>
		</div>
	</lay-layer>
</template>

<script setup>
	import { ref, getCurrentInstance } from 'vue';
	import polTable from '@/components/polTable/polTable.vue'; //表格组件

	const { proxy } = getCurrentInstance();

	const props = defineProps({
		//当前操作的事件
		title: {
			type: String,
			default: '',
		},
		//导入模板类型，2员工
		targetKey: {
			type: String,
			default: '',
		}
	});
	const emit = defineEmits(['importExcelSuc'])
	
	const loading = ref(false) //laoding
	const formRef = ref(null) //表单ref
	const visible = ref(false);
	const area = ref(['1200px', '800px'])
	const fileUrl = ref() //下载模板链接地址
	const importFileName = ref() //下载导入模板路径名称
	const exts = ref(["xls", "xlsx", "csv", "docx", "doc"])
	const ext = ref() //导入文件的后缀名
	const importFile = ref() //导入文件file
	const layUploadKey = ref(new Date().getTime())	//上传组件的key用来刷新组件，解决同一个文件第二次上传时无法监听回调问题
	// 表单数据
	const model = {
		TargetKey: props.targetKey, //目标表
		SheetIndex: '0', //导入第几张表
		RowIndex: '1', //从第几行导入
		MatchMode: '1', //匹配方式.
		filename: '', //文件路径
		StrBase64: '', //文件base64
		files: '', //导入的文件
		TargetTable: '' //导入模板名称
	};

	const formData = ref(JSON.parse(JSON.stringify(model)));

	//表单配置
	const formSchema = ref({
		TargetKey: {
			label: '目标表',
			type: 'select',
			required: true,
			props: {
				options: [],
				placeholder: '请选择目标表',
			}
		},
		SheetIndex: {
			label: '导入第几张表',
			required: false,
			hidden: false,
			slots: {
				customRender: 'SheetIndex',
			},
			colProps: {
				md: 12,
			},
		},
		RowIndex: {
			label: '从第几行导入',
			required: false,
			hidden: false,
			slots: {
				customRender: 'RowIndex',
			},
			colProps: {
				md: 12,
			},
		},
		MatchMode: {
			label: '匹配方式',
			type: 'select',
			hidden: false,
			props: {
				options: [
					{ label: '列标题', value: '1' }
				],
				placeholder: '请选择匹配方式',
			}
		},
		filename: {
			label: '文件路径',
			slots: {
				customRender: 'filename',
			}
		},
		importTemplate: {
			label: '导入模板',
			slots: {
				customRender: 'importTemplate',
			}
		},
	});

	//获取导入配置
	function getImportConfig() {
		const params = {
			targetKey: props.targetKey
		}
		proxy.$http.comm.getImportConfig(params).then(res => {
			let d = res.data;
			let TempFile = d.TempFile;

			//目标表
			const TargetKeyList = [
				{ label: d.TableDesc, value: d.TargetKey },
			]
			formSchema.value.TargetKey.props.options = TargetKeyList
			formData.value.TargetTable = d.TableName
			//导入模板
			if (TempFile) {
				let temp = TempFile.substr(TempFile.lastIndexOf('/') + 1, TempFile.length);
				let extName = /[.]/.exec(temp) ? /[^.]+$/.exec(temp)[0] : undefined;
				ext.value = extName
				if (exts.value?.indexOf(extName) >= 0) {
					formShow(false)
				} else {
					formShow(true)
				}

				if (temp) {
					fileUrl.value = `${baseConfig.baseUrl}${TempFile}` //下载导入模板路径
					importFileName.value = temp
				}
			}
		}).catch(err => {

		})
	}

	//控制表单
	function formShow(val) {
		//控制表单显示隐藏
		formSchema.value.SheetIndex.hidden = val
		formSchema.value.RowIndex.hidden = val
		formSchema.value.MatchMode.hidden = val
		//控制表单是否必填
		formSchema.value.SheetIndex.required = !val
		formSchema.value.RowIndex.required = !val
	}

	//选择导入文件
	function onChange(files) {
		let name = files[0].name; //文件名
		var suffix = name.substr(name.lastIndexOf('.') + 1); //扩展名
		if (ext.value?.indexOf(suffix) == -1) {
			proxy.$msg.err("选择的文件格式不正确，只有选择扩展名为[" + ext.value + "]的文件");
			return false;
		}
		action.value[0].disabled = true
		action.value[1].disabled = true
		importFile.value = files[0]
		formData.value.filename = name //赋值给文本框
		formData.value.files = name
		
		layUploadKey.value = new Date().getTime()
	}

	//表格配置
	const polTableKey = ref(0) //表格key用来刷新表格
	const tableOpt = ref({
		columns: [],
		localData: [], //本地数据
		height: '320px',
		isAutoHttp: false,
		defaultToolbar: false, //是否显示工具栏右边按钮
		showPermissionBtn: false, //是否显示工具栏权限按钮
		showCkb: false, //显示复选框
		rowStyle: rowStyle, //设置行的样式
		even: false, //是否开启条纹--会影响设置错误背景颜色
	});

	//读取数据事件
	function onUpload() {
		if (!importFile.value) {
			proxy.$msg.err("请选择需要上传的一个文件");
			return false;
		}
		if (loading.value) return

		let fr = new FileReader();
		fr.readAsDataURL(importFile.value); //通过文件流将文件转换成Base64字符串
		fr.onload = function(e) {
			// 结果
			let base64 = e.target.result;
			let name = importFile.value.name; //文件名
			var suffix = name.substr(name.lastIndexOf('.')); //扩展名
			base64 = suffix + "|" + base64;
			formData.value.StrBase64 = base64;

			loading.value = true
			let loadingIndex = proxy.$msg.loading()
			proxy.$http.comm.importUplExcel(formData.value).then(res => {
				let d = res.data;
				let ext = /[.]/.exec(suffix) ? /[^.]+$/.exec(suffix)[0] : undefined;
				let isWord = exts.value?.indexOf(ext) < 0;

				if (isWord) { //word
					tableOpt.value.columns = [
						{ title: '名称', width: '30%', key: 'FieldTitle', align: 'center' },
						{ title: '值', width: '70%', key: 'FieldValue', align: 'center', customSlot: 'FieldValue' },
					];
				} else { //excel
					let cols = []
					d.cols.forEach(item => {
						const colsItem = {
							title: item.title,
							width: '130px',
							key: item.fieldname,
							align: 'center',
							customSlot: item.fieldname,
							required: item.required
						}
						cols.push(colsItem)
					})
					//添加删除列
					const removeItem = {
						title: '#',
						width: '90px',
						key: 'remove',
						align: 'center',
						customSlot: 'remove',
						fixed: 'right'
					}
					cols.push(removeItem)

					tableOpt.value.columns = cols;
				}

				tableOpt.value.localData = d.data

				action.value[0].disabled = false
				polTableKey.value = new Date().getTime()
				loading.value = false
				proxy.$msg.close(loadingIndex) //关闭loading
			}).catch(err => {
				loading.value = false
				proxy.$msg.close(loadingIndex) //关闭loading
			})
		};
	}

	//删除行
	function removeRow(rowIndex) {
		console.log(rowIndex)
		tableOpt.value.localData.splice(rowIndex, 1);
	}

	//确定提交
	const action = ref([{
			text: '校验数据',
			disabled: true,
			callback: () => {
				if (tableOpt.value.localData.length === 0) return proxy.$msg.err('需要导入的数据为空！')
				if (loading.value) return

				let params = JSON.parse(JSON.stringify(formData.value))
				params.list = tableOpt.value.localData

				loading.value = true
				let loadingIndex = proxy.$msg.loading()
				proxy.$http.comm.checkImpData(params).then(res => {
					loading.value = false
					proxy.$msg.close(loadingIndex) //关闭loading
					tableOpt.value.localData = res.data
					//如果数据完全正确，则可上传
					//先移除，如有出错的，再加上样式和属性，限制导入按钮的点击
					if (JSON.stringify(res.data).indexOf("ERROR") != -1) {
						proxy.$msg.err("发现数据有误，请先修改错误！");
						action.value[1].disabled = true
					} else {
						action.value[1].disabled = false
					}
					polTableKey.value = new Date().getTime()
				}).catch(err => {
					loading.value = false
					proxy.$msg.close(loadingIndex) //关闭loading
				})
			},
		},
		{
			text: '开始导入',
			disabled: true,
			callback: () => {
				if (tableOpt.value.localData.length === 0) return proxy.$msg.err('需要导入的数据为空！')
				if (JSON.stringify(tableOpt.value.localData).indexOf("ERROR") != -1) return proxy.$msg.err("导入的数据包含有错误内容，请核查！");
				if (loading.value) return

				let params = JSON.parse(JSON.stringify(formData.value))
				params.list = tableOpt.value.localData;

				loading.value = true
				let loadingIndex = proxy.$msg.loading()
				proxy.$http.comm.importExcel(params, false).then(res => {
					loading.value = false
					proxy.$msg.close(loadingIndex) //关闭loading
					if (res.code == 100) {
						isConfirmFn(res, params);
						return;
					}
					visible.value = !visible.value;
					emit('importExcelSuc')	//成功通知父组件
				}).catch(err => {
					loading.value = false
					proxy.$msg.close(loadingIndex) //关闭loading
					if (err.code == 100) {
						isConfirmFn(err, params)
					}
				})
			},
		},
		{
			text: '取消',
			callback: () => {
				visible.value = !visible.value;
			},
		},
	]);

	// 提交导入返回值为100时 弹出询问
	function isConfirmFn(err, params) {
		layer.confirm(err.msg, {
			btn: [{
					text: '确定',
					callback: (id) => {
						//导入数据
						if (loading.value) return
						loading.value = true
						let loadingIndex = proxy.$msg.loading()
						
						proxy.$http.comm.importExcel(params, true).then(res => {
							loading.value = false
							proxy.$msg.close(loadingIndex) //关闭loading
							proxy.$msg.info(res.msg)
							visible.value = !visible.value;
							emit('importExcelSuc')	//成功通知父组件
							layer.close(id);
						}).catch(err => {
							loading.value = false
							proxy.$msg.close(loadingIndex) //关闭loading
						})
					},
				},
				{
					text: '取消',
					callback: (id) => {
						layer.close(id);
					},
				},
			],
		});
	}

	//设置行样式
	function rowStyle(row, rowIndex) {
		if (JSON.stringify(row).indexOf("ERROR") != -1) {
			return 'background-color: rgba(255, 87, 36,0.3)'
		}
	}

	//控制导入弹窗显示隐藏
	function showPolImport() {
		getImportConfig()
		visible.value = !visible.value;
	}

	defineExpose({
		showPolImport
	});
</script>

<style lang="scss">

</style>